package com.rd.server.modules.room.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.rd.common.model.Result;
import com.rd.modules.group.AddGroup;
import com.rd.modules.room.model.ao.RoomAO;
import com.rd.modules.room.model.ao.RoomTransferAO;
import com.rd.modules.room.model.vo.RoomTransferVO;
import com.rd.modules.room.model.vo.RoomUsersVO;
import com.rd.server.modules.room.model.RoomPO;
import com.rd.server.modules.room.model.RoomTransferPO;
import com.rd.server.modules.room.model.RoomUsersPO;
import com.rd.server.modules.room.service.RoomService;
import com.rd.server.modules.room.service.RoomTransferService;
import com.rd.server.modules.room.service.RoomUsersService;
import com.rd.server.modules.sse.service.SseService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.rd.server.modules.room.model.table.RoomTableDef.ROOM;
import static com.rd.server.modules.room.model.table.RoomTransferTableDef.ROOM_TRANSFER;


/**
 * 房间管理
 */
@RestController
@RequestMapping("/rooms")
public class RoomController {

    @Resource
    private RoomService roomService;

    @Resource
    private RoomTransferService roomTransferService;

    @Resource
    private RoomUsersService roomUsersService;

    @Resource
    private SseService sseService;

    /**
     * 创建房间
     *
     * @return
     */
    @PostMapping("create-room")
    public Result<String> createRoom() {
        // 查询用户是否有未结算房间
        String userId = StpUtil.getLoginIdAsString();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ROOM.STATUS.getName(), 0);
        queryWrapper.eq(ROOM.CREATED_ID.getName(), userId);
        queryWrapper.orderBy(ROOM.CREATED_AT.getName());
        List<RoomPO> list = roomService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            return Result.success(list.getLast().getId());
        }

        String roomId = roomService.createRoom();

        sseService.joinRoom(roomId);
        return Result.success(roomId);
    }


    /**
     * 房间结算
     *
     * @param roomAO
     * @return
     */
    @PostMapping("close-room")
    public Result<String> closeRoom(@Validated @RequestBody RoomAO roomAO) {
        String userId = StpUtil.getLoginIdAsString();
        RoomUsersPO roomUsersPO = roomUsersService.selectByUserIdAndRoomId(userId, roomAO.getRoomId());
        if (Objects.isNull(roomUsersPO)) {
            return Result.error("没有权限操作该房间");
        }
        roomService.closeRoom(roomAO);
        return Result.success();
    }


    /**
     * 转账
     *
     * @param transferList 转账实体集合
     * @return
     */
    @PostMapping("transfer")
    public Result<String> transfer(@Validated(AddGroup.class) @RequestBody List<RoomTransferAO> transferList) {
        if (CollectionUtils.isEmpty(transferList)) {
            return Result.error("参数不能为空！");
        }
        RoomTransferAO transfer = transferList.getFirst();
        String userId = StpUtil.getLoginIdAsString();
        RoomUsersPO roomUsersPO = roomUsersService.selectByUserIdAndRoomId(userId, transfer.getRoomId());
        if (Objects.isNull(roomUsersPO)) {
            return Result.error("没有权限操作该房间");
        }
        for (RoomTransferAO roomTransfer : transferList) {
            if (StringUtils.equals(userId, roomTransfer.getRecipientUserId())) {
                return Result.error("不能给自己转账");
            }
        }
        for (RoomTransferAO roomTransfer : transferList) {
            roomService.transfer(roomTransfer);
        }
        return Result.success();
    }


    /**
     * 房间详情（用户列表）
     *
     * @param roomId 房间ID
     * @return 用户列表
     */
    @GetMapping("info/{roomId}")
    public Result<List<RoomUsersVO>> getRoomInfo(@PathVariable String roomId) {
        // 查询用户是否在房间里面
        String userId = StpUtil.getLoginIdAsString();
        RoomUsersPO roomUsersPO = roomUsersService.selectByUserIdAndRoomId(userId, roomId);
        if (Objects.isNull(roomUsersPO)) {
            return Result.error("没有权限进入该房间");
        }
        List<RoomUsersPO> roomUsersPOS = roomUsersService.selectByRoomId(roomId);
        List<RoomUsersVO> roomTransferList = BeanUtil.copyToList(roomUsersPOS, RoomUsersVO.class);
        RoomPO roomPO = roomService.getById(roomId);
        String roomOwnerId = null;
        for (RoomUsersVO roomUsersVO : roomTransferList) {
            roomUsersVO.setIsRoomAdmin(false);
            if (StringUtils.equals(roomUsersVO.getUserId(), roomPO.getCreatedId())) {
                roomUsersVO.setIsRoomAdmin(true);
                roomOwnerId = roomUsersVO.getUserId();
            }
        }
        this.sortRoomUsers(roomTransferList, roomOwnerId);
        return Result.success(roomTransferList);
    }


//    /**
//     * 房间详情（转账记录列表）
//     * @param roomId
//     * @return 转账记录列表
//     */
//    @GetMapping("/record/{roomId}")
//    public Result<List<RoomTransferVO>> getRoomRecord(@PathVariable String roomId) {
//        String userId = StpUtil.getLoginIdAsString();
//        RoomUsersPO roomUsersPO = roomUsersService.selectByUserIdAndRoomId(userId, roomId);
//        if (Objects.isNull(roomUsersPO)) {
//            return Result.error("没有权限进入该房间");
//        }
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq(ROOM_TRANSFER.ROOM_ID.getName(), roomUsersPO.getRoomId());
//        queryWrapper.orderBy(ROOM_TRANSFER.CREATED_AT.getName(),Boolean.FALSE);
//        List<RoomTransferPO> list = roomTransferService.list(queryWrapper);
//        List<RoomTransferVO> roomTransferVOS = BeanUtil.copyToList(list, RoomTransferVO.class);
//        return Result.success(roomTransferVOS);
//    }

    /**
     * 房间详情（转账记录列表）
     *
     * @param roomId        房间ID
     * @param lastCreatedAt 最后一条数据的创建时间（时间戳）
     * @param pageSize      条数（默认10条）
     * @return 转账记录列表
     */
    @GetMapping("/record/{roomId}")
    public Result<List<RoomTransferVO>> getRoomRecord(@PathVariable String roomId, @RequestParam(required = false) Date lastCreatedAt, @RequestParam(defaultValue = "10") Integer pageSize) {
        String userId = StpUtil.getLoginIdAsString();
        RoomUsersPO roomUsersPO = roomUsersService.selectByUserIdAndRoomId(userId, roomId);
        if (roomUsersPO == null) {
            return Result.error("没有权限进入该房间");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ROOM_TRANSFER.ROOM_ID.getName(), roomId);
        if (lastCreatedAt != null) {
            queryWrapper.lt(ROOM_TRANSFER.CREATED_AT.getName(), lastCreatedAt);
        }
        queryWrapper.orderBy(ROOM_TRANSFER.CREATED_AT.getName(), false);
        queryWrapper.limit(pageSize);

        List<RoomTransferPO> list = roomTransferService.list(queryWrapper);
        List<RoomTransferVO> vos = BeanUtil.copyToList(list, RoomTransferVO.class);
        return Result.success(vos);
    }


    /**
     * 对房间用户进行排序
     * 排序规则：
     * 1. 房主排在最前面
     * 2. 其他用户按加入时间排序（先加入的在前）
     * 3. 指定用户（ID: 288942432152104960）排在最后
     *
     * @param userList    用户列表
     * @param roomOwnerId 房主ID
     * @return 排序后的用户列表
     */
    private List<RoomUsersVO> sortRoomUsers(List<RoomUsersVO> userList, String roomOwnerId) {
        if (userList == null || userList.isEmpty()) {
            return userList;
        }

        // 指定要排到最后的用户ID
        String specifiedUserId = "288942432152104960";

        return userList.stream().sorted((user1, user2) -> {
            // 1. 房主优先
            boolean isUser1Owner = StringUtils.equals(user1.getUserId(), roomOwnerId);
            boolean isUser2Owner = StringUtils.equals(user2.getUserId(), roomOwnerId);

            if (isUser1Owner && !isUser2Owner) {
                return -1; // user1是房主，排前面
            }
            if (!isUser1Owner && isUser2Owner) {
                return 1;  // user2是房主，排前面
            }

            // 2. 指定用户排在最后
            boolean isUser1Specified = StringUtils.equals(user1.getUserId(), specifiedUserId);
            boolean isUser2Specified = StringUtils.equals(user2.getUserId(), specifiedUserId);

            if (isUser1Specified && !isUser2Specified) {
                return 1;  // user1是指定用户，排后面
            }
            if (!isUser1Specified && isUser2Specified) {
                return -1; // user2是指定用户，排后面
            }

            // 3. 其他用户按加入时间排序（先加入的在前）
            if (user1.getCreatedAt() != null && user2.getCreatedAt() != null) {
                return user1.getCreatedAt().compareTo(user2.getCreatedAt());
            }

            return 0;
        }).collect(Collectors.toList());
    }

}